package com.zwj.interview.缓存;

import java.util.LinkedHashMap;

/**
 * @Author: Zwj
 * @Date: 2022/2/27 11:23
 * 使用java中的LinkedHashMap来实现
 */
public class LRUCacheInJava {

    int cap;
    LinkedHashMap<Integer,Integer> cache=new LinkedHashMap<>();
    public LRUCacheInJava(int capacity){
        this.cap=capacity;
    }

    public int get(int key){
        if(!cache.containsKey(key)){
            return -1;
        }
        makeRecently(key);
        return cache.get(key);
    }

    public void put(int key,int val){
        if(cache.containsKey(key)){
            cache.put(key,val);
            makeRecently(key);
            return;
        }
        if(cache.size()>=this.cap){
            int oldestKey=cache.keySet().iterator().next();
            cache.remove(oldestKey);
        }
        cache.put(key,val);
    }

    private void makeRecently(int key) {
        int val=cache.get(key);
        cache.remove(key);
        cache.put(key,val);
    }

}